//spec is at: https://www.ietf.org/rfc/rfc791.txt

#include "network_filter_ipv4.h"

#include "assert.h"

#include "../../Include/network_struct.h"

#include "stdio.h"

network_filter_ipv4::network_filter_ipv4()
	:network_filter_base( FAD_ETHERNET , FAD_IP )
{
}


network_filter_ipv4::~network_filter_ipv4()
{
}

void network_filter_ipv4::process_network_data(FILTER_ACCEPT_DATATYPE type, void * ptr_data)
{
	assert(type == FAD_ETHERNET);

	network_ethernet_data * ptr_ethernet = (network_ethernet_data *)ptr_data;

    ipv4_data * ptr_ipv4_data = m_parser.parse( ptr_ethernet );
    
    if( !ptr_ipv4_data )
        return;
    
    network_ipv4_data data;
    data.time = ptr_ethernet->time;
    memcpy( data.ether_shost , ptr_ethernet->ether_shost , ETHER_ADDR_LEN );
    memcpy( data.ether_dhost , ptr_ethernet->ether_dhost , ETHER_ADDR_LEN );

	ptr_ipv4_data->ptr_data->add_ref();
    
    int ret = m_defragmentor.defragment( ptr_ipv4_data , &data );
    
	if (ret == 0)
	{
		send_network_data(FAD_IP, &data);
		data.ptr_data->release();
	}
    else
        return;
    
    /*printf( "Ver %d\tHeader Size %d\tTotal %d\tID %d\t%s\t%s\tOffset %d\t%d",
           ptr_ipv4_data->version,
           ptr_ipv4_data->header_length,
           ptr_ipv4_data->total_length,
           ptr_ipv4_data->identification,
           ptr_ipv4_data->will_fragment?"May Frag":"No  Frag",
           ptr_ipv4_data->is_last_fragment?"Is Last":"No Last",
           ptr_ipv4_data->fragment_offset,
           ptr_ipv4_data->ttl);
    
    switch ( ptr_ipv4_data->protocol ) {
        case IPPROTOCOL_ICMP:
            printf( "\tICMP\t" );
            break;
        case IPPROTOCOL_TCP:
            printf( "\tTCP \t" );
            break;
        case IPPROTOCOL_UDP:
            printf( "\tUDP \t" );
            break;
        default:
            printf( "\tUnkwn\t" );
            break;
    }
    
    printf( "Src: %d:%d:%d:%d Dest: %d:%d:%d:%d\n",
           ptr_ipv4_data->saddr[0],
           ptr_ipv4_data->saddr[1],
           ptr_ipv4_data->saddr[2],
           ptr_ipv4_data->saddr[3],
           ptr_ipv4_data->daddr[0],
           ptr_ipv4_data->daddr[1],
           ptr_ipv4_data->daddr[2],
           ptr_ipv4_data->daddr[3]);*/
}





